package cn.itcast.web.shiro;

import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;

    @Override //用户登陆成功之后就会调用该方法给用户去授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //得到登陆成功用户对象
        User user = (User) principals.getPrimaryPrincipal();
        //得到用户拥有的权限
        System.out.println("============TayTay============");
        List<Module> list = moduleService.findModuleByUser(user);
        //把用户权限的标记添加到authoriztionInfo集合
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (Module module : list) {
            simpleAuthorizationInfo.addStringPermission(module.getName());
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 认证的方法
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("=================");
        //把token转换为UsernamePasswordToken因为可以使用子类特有的方法
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String email = usernamePasswordToken.getUsername();
//      使用用户名去查询一个用户 如果为null，则返回null，如果该方法返回null，
//那么login方法马上会收到unkownAccountException
        User user = userService.findByEmail(email);
        if (user==null){
            return null;
        }
        /**
         * SimpleAuthenticationInfo方法参数的说明
         * object principal 登陆成功返回的对象
         * object credentials,该用户在数据库中的密码
         * String realmName 不需要
         */
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), "");
        return simpleAuthenticationInfo;

    }
}
